<?php
require_once("model/Photo.php");
define("MAX_SIZE","10000");

function uploadImg($file,$key){
	$valid_formats = array("jpg","png","gif","bmp","jpeg");
	
	$photo = null;
	try{
		$name = $file[$key]["name"];
		$size = $file[$key]["size"];
		if(strlen($name)){
			list($txt,$ext) = explode(".", $name);
			$ext = strtolower($ext);
			
			$photo = new Photo();
			$photo->imageName = $name;
			$photo->imageSize = $size;
			$photo->ext = $ext;
			$photo->imageType = $file[$key]["type"];
			
			if(in_array($ext,$valid_formats)){
				if($size < MAX_SIZE*1024){
					$uploadedfile = $file[$key]["tmp_name"];
					if($ext == "jpg" || $ext == "jpeg"){
						$src = imagecreatefromjpeg($uploadedfile);
					}
					else if($ext == "png"){
						$src = imagecreatefrompng($uploadedfile);
					}
					else{
						$src = imagecreatefromgif($uploadedfile);
					}
					
					list($width,$height)=getimagesize($uploadedfile);
					
					$newwidth = 600;
					$newheight = $height*($newwidth/$width);
					$tmp = imagecreatetruecolor($newwidth,$newheight);
						
					$newwidth1 = 200;
					$newheight1 = $height*($newwidth1/$width);
					$tmp1 = imagecreatetruecolor($newwidth1,$newheight1);
						
					$newwidth2 = 75;
					$newheight2 = ($height/$width)*$newwidth2;
					$tmp2 = imagecreatetruecolor($newwidth2,$newheight2);
					
					imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
						
					imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
						
					imagecopyresampled($tmp2,$src,0,0,0,0,$newwidth2,$newheight2,$width,$height);
					
					$filename = "tmp/".$_SESSION["me"]->playerid."_".$name;
					$filename1 = "tmp/med_".$_SESSION["me"]->playerid."_".$name;
					$filename2 = "tmp/thumb_".$_SESSION["me"]->playerid."_".$name;
					
					imagejpeg($tmp,$filename,100);
					imagejpeg($tmp1,$filename1,100);
					imagejpeg($tmp2,$filename2,100);
					
					
					
					$photo->imageDataLarge = file_get_contents($filename); 
					$photo->imageDataMed = file_get_contents($filename1);
					$photo->imageDataThumb = file_get_contents($filename2);
					
					imagedestroy($src);
					imagedestroy($tmp);
					imagedestroy($tmp1);
					imagedestroy($tmp2);
					unlink($filename);
					unlink($filename1);
					unlink($filename2);		
				}
			}
		}
	}
	catch(Exception $e){
		throw new Exception("error in ". __CLASS__);
	}
	return $photo;
}
?>